﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckNoRecentBackup : IssueTypeCheckBase
    {

        public DatabaseCheckNoRecentBackup()
        {
            IssueTypeId = 3002;
        }

        public override void Check()
        {

            // Create a Data Context 
            HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
            Issue issue = new Issue();
            DateTime previousWorkingDay = GetPreviousWorkDay();

            
            // Create a link Query 
            var qry = from d in dc.Databases

                      where
                      (d.LatestDifferentialBackup.HasValue == false && d.LatestFullBackup.HasValue == false)

                      ||

                      (d.LatestDifferentialBackup.HasValue == true && d.LatestFullBackup.HasValue == true) && 
                      (d.LatestFullBackup >= GetPreviousWorkDay() || d.LatestDifferentialBackup >= GetPreviousWorkDay())


                      ||

                      ((d.LatestFullBackup.HasValue == true && d.LatestDifferentialBackup.HasValue == false) && 
                      (d.LatestFullBackup >= GetPreviousWorkDay()))

                      select d;

            // Iterate through the Linq Query 
            foreach (var item in qry)
            {
                int databaseId = item.DatabaseID;
                //Get Issuetype object

                //Get Issuetype object  And Create a new  Global issue object 
                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                //                
                issue.IssueType = issueType;
                issue.TargetId = databaseId;
                issue.Description = issueType.Description.Replace("{Database}", item.DatabaseName);

                dc.Issues.InsertOnSubmit(issue);
            }

            dc.SubmitChanges();
        }

        public static DateTime GetPreviousWorkDay()
        {

            // check wether the previous day is a working day 
            if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
            {
                return DateTime.Today.AddDays(-2);
            }
            else if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
            {
                return DateTime.Today.AddDays(-3);
            }
            else
            {
                return DateTime.Today.AddDays(-1);

            }

        }


    }
}
